from datetime import datetime
from sqlalchemy.orm import relationship
from .db import Base
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Boolean

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, index=True, nullable=False)    # 用户名唯一
    password = Column(String(255), nullable=False)                            # 哈希密码
    email = Column(String(100), unique=True, index=True, nullable=True)       # 邮箱唯一
    phone = Column(String(20), unique=True, index=True, nullable=True)        # 手机号唯一
    role = Column(String(20), default="user", nullable=False)                 # 角色字段
    created_at = Column(DateTime, default=datetime.utcnow)
    doctor_id = Column(Integer, ForeignKey("users.id"), nullable=True)

    # ORM 关系（医生-患者）
    doctor = relationship("User", remote_side=[id], backref="patients")

    def __repr__(self):
        return f"<User(username={self.username}, role={self.role})>"


class Alert(Base):
    __tablename__ = "alerts"

    id = Column(Integer, primary_key=True, autoincrement=True)
    device_id = Column(String(64), ForeignKey("devices.device_id"))
    owner = Column(String(50), ForeignKey("users.username"))
    message = Column(String(255))
    timestamp = Column(DateTime, default=datetime.utcnow)
    resolved = Column(Boolean, default=False)
    ecg_record_id = Column(Integer, ForeignKey("ecg_records.id"))  # 关联ECG记录
